<template>
  <div>

      <el-form :model="formData" ref="form" :rules="rules" label-width="80px" :inline="true" size="normal"
          class="demo-fore-inline">
          <div>
            <el-form-item label="客户">
                  <el-select v-model="formData.supId" style="width: 120px;">
                      <el-option 
                      v-for="item in supname" :key="item.supId" 
                      :label="item.supName" :value="item.supId"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="单据日期" prop="date">
                  <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
              </el-form-item>
              <el-form-item label="单据编号" prop="documentnumber">
                  <el-input v-model="formData.number"></el-input>
              </el-form-item>

          </div>
          <div>
              <el-form-item>
                  <el-button plain @click="insertTr" type="primary">插入行</el-button>
               
                  <el-button plain>扫码录入</el-button>
              </el-form-item>
          </div>
          <div class="ant-col" style="margin-right: 10px;">
      
      </div>
      </el-form>
      <el-table :data="tableData" show-summary style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column label="仓库" width="120">
          <template #default="{ row }">
            <el-select v-model="row.dname" clearable style="width: 280px; margin-left: 10px;" placeholder="请选择仓库"
              @change="onChangeDepotSelect(row.dname)">
              <el-option v-for="depot in depots" :key="depot.id" :label="depot.name" :value="depot.id" />
            </el-select>
          </template>
        </el-table-column>
      <el-table-column width="120">
        <template #default="{ row }">

          <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
             v-perm:depot:other_back:insert:info="info">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
            </el-button>
        </template>
      </el-table-column>
      <el-table-column label="条码" width="120">
        <template #default="{ row }">
          <el-input v-model="row.barCode"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="120">
        <template #default="{ row }">
          <el-input v-model="row.materialName"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格" width="120">
        <template #default="{ row }">
          <el-input v-model="row.standard"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="库存" width="120">
        <template #default="{ row }">
          <el-input v-model="row.totalOperNumber"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单位" width="120">
        <template #default="{ row }">
          <el-input v-model="row.commodityUnit"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="120">
        <template #default="{ row }">
          <el-input v-model="row.operNumber" @change="inputNumberChange(row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单价" width="120">
        <template #default="{ row }">
          <el-input v-model="row.wholesaledecimal"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="金额" width="120">
        <template #default="{ row }">
          <el-input v-model="row.allPrice"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="100">
        <template #default="{ row }">
          <el-input v-model="row.totalOut"></el-input>
        </template>
      </el-table-column>
    </el-table>
      <el-form-item style="">
          <el-button plain @click="onSubmit" type="primary">确定</el-button>
              <el-button>重置</el-button>
      </el-form-item>
  </div>

<el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="70%"
  style="margin-left: 350px;margin-top: 200px">
  <router-view @close="closeDialog" @saveSaleinorder="saveSaleinorder" :data="data" :currentDepotId="currentDepotId"></router-view>
</el-dialog>
</template>
<script setup>
// 导入Vue中的ref和defineEmits函数
import { ref, defineEmits,onMounted } from 'vue'
import { ElMessage } from "element-plus";

// 使用ref函数创建一个响应式的数据
// 使用defineEmits函数定义可以触发的自定义事件
import request from '@/api/request'
import router from '@/router';
import reqeust from '@/api/request'


let formData = ref({})

let emits = defineEmits(['close'])
let ruleForm = ref({})
const tableData = ref([
{ barCode: '', categoryName: '', color: '', commodityUnit: '', materialName: '', mfrs: '', model: '', sku: '', standard: '', totalIn: '', totalOperNumber: '', totalOut: '', wholesaledecimal: '', basicnumber: '', allprice: '' ,id:''}
]);

const inputNumberChange = (row) => {
console.log(row)

row.allPrice = row.wholesaledecimal * row.operNumber
console.log(row.allPrice);

}
const visible = ref(false);
const title = ref("");
const data = ref({});

//新增插入行
const insertTr = () => {
  tableData.value.push({
    barCode: '',
    categoryName: '',
    color: '',
    commodityUnit: '',
    materialName: '',
    mfrs: '',
    model: '',
    sku: '',
    standard: '',
    totalIn: '',
    totalOperNumber: '',
    totalOut: '',
    wholesaledecimal: '',
    basicnumber: '',
    allPrice: '',
    mid: '',
    aid: '',
    id: '',
    operNumber: 1, // 默认数量
    taxRate: '',
    taxMoney: '',
    taxLastMoney: '',
    dname: '',
    depotId: '' // 新行的仓库默认空值
  });
};
// submitTable();
let submitTable = ()=>{
  console.log(tableData.value)
}
onMounted(() => {
// 从本地存储获取当前的订单编号，如果不存在则默认为1
let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);

// 自增
currentOrderNumber++;

// 格式化为10位数
const formattedOrderNumber = currentOrderNumber.toString().padStart(10, '0');

// 将生成的订单编号赋值到表单
formData.value.number = 'QTCK' + formattedOrderNumber;

// 将新的订单编号存储到本地存储中，便于下次使用
localStorage.setItem('orderNumber', currentOrderNumber.toString());
});
console.log(formData.value.id);
//多表查询
let onSubmit = () => {
  const data = {
      erpDepotHead: {
          type:'出库',
          subType:'其它',
          organId: formData.value.supId,
          number: formData.value.number,
          creator: '1',
          changeAmount: '0',
          totalPrice: tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0), // 计算合计金额
          status: '0'
      },
      erpDepotItems: tableData.value.map(row => ({
          materialId: row.mid,
          materialExtendId: row.aid,
          materialUnit: row.commodityUnit,
          sku: row.sku,
          operNumber: row.operNumber,
          depotId: row.depotname,
          unitPrice: row.wholesaledecimal,
          allPrice: row.allPrice,
          remark: row.remark || '',
          taxRate: row.taxRate,
          taxMoney: row.taxMoney,
          depotId:row.dname
      }))
  };


  // if(!data.erpDepotHead.organId){
  //   ElMessage.warning('请填写订单编号');  
  //   return; 
  // }

  for (const row of tableData.value) {
        if (!row.operNumber) {
            ElMessage.error('请填写数量');
            return;  // 退出函数
        }
    }
  

  
  
  reqeust({
      url:'/sale/insertdepot',
      method:'post',
      data:data,
      headers: { 'Content-Type': 'application/json' }
  }).then(resp=>{
      close();
      console.log(resp)
  })
}

let close=()=>{
  emits('close')
}

let closeDialog =()=>{
  visible.value = false
}

let supname = ref([])
reqeust.get('/depot/findSupplier'+'/'+1,{method:'get'}).then(resp => {
  console.log(resp);
  
  supname.value = resp.data
})
const depots = ref([]);
const loadDepot = () => {
request({
  url: '/depot/list',
  method: 'get'
}).then(res => {
  depots.value = res.data; // 更新仓库数据
}).catch(err => {
  console.error(err);
});
};
loadDepot();
let randomID = ""
let generateRandomID=()=>{
  const characters ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   const idLength = 16; // 字符串长度这里生成16位的 
  
      for (let i = 0; i< idLength; i++){
      const randomIndex = Math.floor(Math.random()* characters.length); 
      randomID += characters.charAt(randomIndex);
  }
console.log(randomID)
return randomID;
}
generateRandomID();

const info = (p) => {
title.value = p.cname;
visible.value = true;
router.push(p.path);
};
const onChangeDepotSelect = (depotId) => {
    currentDepotId.value = depotId; // 更新当前选择的仓库 ID
};

const currentDepotId = ref('');
// 接收并显示保存的数据a
const saveSaleinorder = (selectedItems) => {
  selectedItems.forEach(item => {
    const emptyRowIndex = tableData.value.findIndex(row => !row.barCode); // 查找第一个空行
    if (emptyRowIndex !== -1) {
      // 将选中的商品填入空行
      const row = tableData.value[emptyRowIndex];
      Object.assign(row, {
        barCode: item.barCode,
        categoryName: item.categoryName,
        color: item.color,
        commodityUnit: item.commodityUnit,
        materialName: item.materialName,
        mfrs: item.mfrs,
        model: item.model,
        sku: item.sku,
        standard: item.standard,
        totalIn: item.totalIn,
        totalOperNumber: item.totalOperNumber,
        totalOut: item.totalOut,
        wholesaledecimal: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allPrice: item.allPrice,
        mid: item.mid,
        aid: item.aid,
        operNumber: 1, // 默认数量
        taxRate: item.taxRate,
        taxMoney: item.taxMoney,
        taxLastMoney: item.taxLastMoney,
        dname: currentDepotId.value, // 使用当前选择的仓库
      });
    } else {
      // 添加新行
      tableData.value.push({
        barCode: item.barCode,
        categoryName: item.categoryName,
        color: item.color,
        commodityUnit: item.commodityUnit,
        materialName: item.materialName,
        mfrs: item.mfrs,
        model: item.model,
        sku: item.sku,
        standard: item.standard,
        totalIn: item.totalIn,
        totalOperNumber: item.totalOperNumber,
        totalOut: item.totalOut,
        wholesaledecimal: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allPrice: item.allPrice,
        mid: item.mid,
        aid: item.aid,
        operNumber: 1, // 默认数量
        taxRate: item.taxRate,
        taxMoney: item.taxMoney,
        taxLastMoney: item.taxLastMoney,
        dname: currentDepotId.value, // 使用当前选择的仓库
      });
    }
  });
  console.log("已添加商品:", selectedItems);
};

</script>

<style scoped>
.demo-fore-inline .el-input {
  --el-input-width: 200px;
}
</style>
